let jwt = require('jsonwebtoken')
const key = 'web26-jwt'

// 产生token方法
function sign(id) {
    // 载体
    let payload = { data: id }
    // 密钥
    let secretOrPrivateKey = key
    //  配置,1天有效期
    let options = { expiresIn: 86400 }
    return jwt.sign(payload, secretOrPrivateKey, options)
}

// 验证token
function verify(token) {
    token = token.substring(7, token.length)
    try {
        let rt = jwt.verify(token, key)
        console.log('your token msg:--------------->', rt)
    } catch (error) {
        return false
    }
    return true
}

function getUserId(req) {
    let token = req.headers['authorization'];
    if (!token) {
        console.log("获取token失败")
        return false;
    }
    token = token.substring(7, token.length)
    let rt = jwt.verify(token, key)
    let userId = rt.data;
    return userId;
}

module.exports = { sign, verify, getUserId }